package alipay

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/wosylf/ltool"
	"gitee.com/wosylf/ltool/pkg/util"
	"gitee.com/wosylf/ltool/pkg/xhttp"
	"gitee.com/wosylf/ltool/pkg/xlog"
)

func (a *Client) F新的文件上传(ctx context.Context, bm ltool.BodyMap, method string, nobizcont ...int) (bs []byte, err error) {

	var (
		bodyStr string
		bodyBs  []byte
		aat     string
		filebm  = make(ltool.BodyMap)
	)
	pubBody := make(ltool.BodyMap)

	pubBody.Set("app_id", a.AppId).
		Set("method", method).
		Set("format", "JSON").
		Set("charset", a.Charset).
		Set("sign_type", a.SignType).
		Set("version", "1.0").
		Set("timestamp", time.Now().Format(util.TimeLayout))

	if bm != nil {
		for k, v := range bm {
			if vvv, ok := v.(*ltool.File); ok {
				filebm.SetFormFile(k, vvv)
				bm.Remove(k)
			}
		}
		aat = bm.GetString("app_auth_token")
		bm.Remove("app_auth_token")
		if bodyBs, err = json.Marshal(bm); err != nil {
			return nil, fmt.Errorf("json.Marshal：%w", err)
		}
		bodyStr = string(bodyBs)
	}

	if a.AppCertSN != util.NULL {
		pubBody.Set("app_cert_sn", a.AppCertSN)
	}
	if a.AliPayRootCertSN != util.NULL {
		pubBody.Set("alipay_root_cert_sn", a.AliPayRootCertSN)
	}
	if a.ReturnUrl != util.NULL {
		pubBody.Set("return_url", a.ReturnUrl)
	}
	if a.location != nil {
		pubBody.Set("timestamp", time.Now().In(a.location).Format(util.TimeLayout))
	}
	if a.NotifyUrl != util.NULL { //如果返回url为空，传过来的返回url不为空
		//fmt.Println("url不为空？", a.NotifyUrl)
		pubBody.Set("notify_url", a.NotifyUrl)
	}
	//fmt.Println("notify,", pubBody.JsonBody())
	if a.AppAuthToken != util.NULL {
		pubBody.Set("app_auth_token", a.AppAuthToken)
	}
	if aat != util.NULL {
		pubBody.Set("app_auth_token", aat)
	}
	if len(nobizcont) == 0 {
		pubBody.Set("biz_content", bodyStr)
	} else {
		for k, v := range bm {
			pubBody.Set(k, v)
		}
	}
	sign, err := GetRsaSign(pubBody, pubBody.GetString("sign_type"), a.privateKey)
	if err != nil {
		return nil, fmt.Errorf("GetRsaSign Error: %w", err)
	}
	pubBody.Set("sign", sign)
	if a.DebugSwitch == ltool.DebugOn {
		xlog.Debugf("Alipay_Request: %s", pubBody.JsonBody())
	}
	//fmt.Println("pubody,", pubBody)
	param := pubBody.EncodeURLParams()
	url := baseUrlUtf8 + "&" + param
	//plug.F打印并且发送消息("请求的url", url)
	if len(filebm) != 0 {
		for k, v := range filebm {
			bm.Set(k, v)
		}
	}
	bm.Reset()
	httpClient := xhttp.NewClient()
	res, bs, err := httpClient.Type(xhttp.TypeMultipartFormData).Post(url).
		SendMultipartBodyMap(filebm).EndBytes(ctx)
	if err != nil {
		return nil, err
	}
	if a.DebugSwitch == ltool.DebugOn {
		xlog.Debugf("Alipay_Response: %s%d %s%s", xlog.Red, res.StatusCode, xlog.Reset, string(bs))
	}
	if res.StatusCode != 200 {
		return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", res.StatusCode)
	}
	return bs, nil
}
